package com.ia2014.tp.portal2.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ia2014.tp.portal2.facades.FacadeVenta;
import com.ia2014.tp.portal2.vo.ItemVentaVO;
/**
 * Realiza de los objetos de portal para 
 * @author DiegoAlejandro
 *
 */
@WebServlet("/verCarrito")
public class VerCarritoServlet extends AbstractServlet {
	private static final long serialVersionUID = 3763571440490518886L;
	
	@EJB
	private FacadeVenta facade;

	public VerCarritoServlet(){
		super();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		this.comprobarSession(req, resp);
		this.process(req, resp);
	
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		this.comprobarSession(req, resp);
		this.process(req, resp);
	
	}	

	private void process(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException{
		
		HttpSession session = req.getSession(false);
		String error = req.getParameter("error");
		if ("1".equals(error)){
			resp.sendRedirect("carrito.jsp?error=1");
		}
		else{
			loadItems(session);
			Integer cantidad = 0;
			Double  precioTotal = 0.0d;
			
			List<ItemVentaVO> items = this.facade.getListaItems();
			if (items == null){
				items = new ArrayList<ItemVentaVO>();
			}
			for (ItemVentaVO item : items){
				cantidad++;
				precioTotal += item.getCantidad() * item.getArticulo().getPrecio();
			}
			
			session.setAttribute("cantidadItemList", cantidad);
			session.setAttribute("precioTotalList", precioTotal);
			session.setAttribute("itemsList", items);
			resp.sendRedirect("carrito.jsp");
		}
	}

	private void loadItems(HttpSession session) throws ServletException, IOException{
		getMapItemsFromSession(session);
		this.facade.setItemsVo(this.itemsVo);
	}
}
